<?php

namespace app\api\controller;

use app\admin\model\SystemUploadfile;
use app\common\controller\HomeBase;
use app\common\model\Article;

use app\common\model\ArticleAttribute;
use app\common\model\Message;
use app\user\model\UserFavorite;
use app\user\model\UserPraise;
use app\common\service\UploadService;
use app\user\model\UserAttribute;
use EasyAdmin\upload\Uploadfile;
use app\user\model\User as Model;
use app\common\model\Comment as Comment;
use QL\Ext\DImage;
use think\App;


class User extends HomeBase
{
    protected $uid;

    public function initialize()
        {
        parent::initialize();
        $this->uid = cacheUserid();
        if (!$this->uid) {
            return json(['code' => 0, 'msg' => '没有登录', 'data' => []]);
        }
        $this->model = new Model();
    }


    public function favorite()
    {
        $params = $this->params;
        $uid=cacheUserid();
        if(!$uid){
           return fail('登录之后才能收藏');
        }
        $res= UserFavorite::note($uid,$params['aid']);
        if($res===true){
            return success('收藏成功');
        }else{
            return json($res);
        }
    }

    public function change_password()
    {
        $only = ['password', 'password_confirm', 'old_password'];
        $rule = [
            'password|密码' => 'require|length:6,18',
            'password_confirm|重复新密码' => 'require|confirm:password'
        ];
        $data = validate_ext($only, $rule);
        if (isset($data['code']) && $data['code'] === 0) {
            return json($data);
        }
        $user = $this->model->find($this->uid);
        if ($user['password'] != '' && $user['password'] != md5($data['old_password'] . $user['salt'])) {
            return json(array('code' => 0, 'msg' => '旧密码输入错误', 'data' => []));
        }
        $user->password = md5($data['password'] . $user['salt']);
        $user->save();
        $redirect = __url('user/index/index');
        return json(array('code' => 1, 'msg' => '密码修改成功',
            'data' => ['reload' => 1]));
    }


    public function common_del()
    {
        $params = $this->params;
        $subject = $params['subject'];
        $modelName = parse_name('user_' . $subject, 1);
        $model = "\\app\\user\\model\\" . $modelName;
        $ret = (new $model())
            ->where('id', $params['id'])
            ->where('user_id', $this->uid)
            ->delete();
        if ($ret) {
            (new UserAttribute())->where('user_id', $this->uid)->dec($subject . '_num', 1)->update();

            return json(['code' => 1, 'msg' => '删除成功', 'data' => ['reload' => 1]]);
        } else {
            return json(['code' => 0, 'msg' => '删除失败', 'data' => []]);
        }

    }

    public function subjects()
    {
        $params = $this->params;

        //必传参数
        $only = ['subject', 'pageIndex', 'pageSize'];
        $rule = [
            'subject|subject' => 'require',
            'pageIndex|pageIndex' => 'require',
            'pageSize|pageSize' => 'require'
        ];
        $data = validate_ext($only, $rule);
        if (isset($data['code']) && $data['code'] === 0) {
            return json($data);
        }
        $subject = $data['subject'];
        $modelName = parse_name('user_' . $subject, 1);
        $where['user_id'] = $this->uid;
        if ($subject == 'article') {
            $model = "\\app\\common\\model\\Article";
        }elseif ($subject == 'comment') {
            $model = "\\app\\common\\model\\Comment";
        } elseif ($subject == 'rechargelog') {
            $model = "\\app\\common\\model\\Order";
            $where['subject'] = 'DEFAULT';
        } else {
            $model = "\\app\\user\\model\\" . $modelName;
        }
        $page = $params['pageIndex'];
        $limit = $params['pageSize'];

        if (isset($params['page'])) {
            $page = $params['page'];
        }
        $model = new $model();

        $count = $model->where($where)->count();
        $list = $model
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $limit)
            ->select();

        foreach ($list as &$v) {
            if ($subject == 'article') {
                $id = $v['id'];
            } else {
                $id = $v['subject_id'];
            }
            $v['url'] = '/html/' . $id . '.html';
        }
        return json(array(
            'code' => 1,
            'msg' => '获取成功',
            'data' => ['list' => $list, 'pager' => [
                'pageSize' => $limit,
                'pageIndex' => $page,
                'count' => $count
            ]],
        ));
    }

    //投稿记录
    public function contributeLog()
    {
        $params = $this->params;

        //必传参数
        $only = ['pageIndex', 'pageSize'];
        $rule = [

            'pageIndex|pageIndex' => 'require',
            'pageSize|pageSize' => 'require'
        ];
        $data = validate_ext($only, $rule);
        if (isset($data['code']) && $data['code'] === 0) {
            return json($data);
        }

        $where['user_id'] = $this->uid;

        $page = $params['pageIndex'];
        $limit = $params['pageSize'];

        if (isset($params['page'])) {
            $page = $params['page'];
        }

        $model=new Article();
        $count = $model
            ->where($where)->count();
        $list = $model
            ->alias('a')
            ->join('article_attribute b','a.id=b.article_id')
            ->where($where)
            ->order('a.id', 'desc')
            ->page($page, $limit)
            ->select();

        foreach ($list as &$v) {
            $v['url'] = '/html/' . $v['article_id'] . '.html';
            $v['info'] = json_encode($v);
        }
        return json(array(
            'code' => 1,
            'msg' => '获取成功',
            'data' => ['list' => $list, 'pager' => [
                'pageSize' => $limit,
                'pageIndex' => $page,
                'count' => $count
            ]],
        ));
    }


    public function record_detail()
    {
        $checkStr = [
            -1 => '无需审核',
            0 => '待审核',
            1 => '审核通过',
            2 => '审核被拒绝',
        ];
        $id = $this->params['id'];
        //先看是不是自己的文章
        $find = (new Article())->where('id', $id)
            ->where('user_id', $this->uid)->find();
        if (!$find) {
            $this->error('不存在');
        }
        $attribute = (new ArticleAttribute())->where('article_id', $id)->find();
        $attribute['check_status'] = $checkStr[$attribute['check_status']];
        $article = array_merge($find->toArray(), $attribute->toArray());
        return json(array('code' => '1', 'msg' => 'success', 'data' => ['data' => $article]));

    }

    public function contribute()
    {
        if (!session('tg_suijima')) {
            return fail('请刷新页面重试');
        }
        //必传参数
        $only = ['title', 'category_id', 'cover_img', 'content', 'attachlink', 'reward_account', 'reward_name', 'type'];
        $rule = [
            'title|标题' => 'require',
            'category_id|分类' => 'require|number',
            'content|内容' => 'require'
        ];
        $data = validate_ext($only, $rule);

        if (isset($data['code']) && $data['code'] === 0) {
            return json($data);
        }
        $userId = $this->uid;
        $title = remove_xss($data['title']);
        $user = cacheUser(1);
        if (!$user['is_admin']) {
            $res = Article::checkAuth($userId);
            if ($res !== true) {
                return $res;
            }
        }
        $data['seo_title'] = $title;
        $noAudit = $user['no_audit'];
        if ($noAudit) {
            $data['status'] = 1;
            $data['publish_time'] = time();
            $msgStr = '发布成功';
        } else {
            $data['check_status'] = 0;
            $msgStr = '请耐心等待审核';
        }
        $data['user_ip'] = request()->ip();
        $data['user_id'] = $userId;
        $content = htmlspecialchars_decode(html_entity_decode($data['content']));

        if(sysconfig('article.downpic')){
            $content=(new DImage())->run([
                'content' => $content,
                'www_root' => $_SERVER['DOCUMENT_ROOT'],
                'image_path' => '/uploads/' . date('Y') . '/' . date('md'),
            ]);
        }

        $data['content'] = $content;
        $cdk = Article::getCDK($content,$title);

        $data['category_id'] = remove_xss($data['category_id']);
        if (isset($data['attachlink'])) {
            $data['attachlink']['user_id'] = $userId;
        }
        $data['keywords'] = $cdk['K'];
        if (isset($data['reward_account'])) {
            //要奖励
            $data['reward_status'] = 0;
        }
        $base64 = $data['cover_img'];
        if ($base64) {
            $resl = UploadService::upBase64($base64);
            if ($resl['code'] == 1) {
                $data['cover_img'] = $resl['data']['url'];
            }
        } else {
            $data['cover_img'] = $cdk['C'];
        }

        try {
            (new Article())->createNew($data);
            session('tg_suijima', null);
            $ret = [
                'code' => 1,
                'msg' => "<i class='layui-icon layui-icon-ok-circle _success'></i>投稿成功！" . $msgStr,
                'data' => ['exempt_num' => 0, 'reload' => 2]
            ];
        } catch (\Exception $e) {
            $ret = [
                'code' => 0,
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
        return json($ret);
    }

    public function changeinfo()
    {
        $uid = $this->uid;
        $find = $this->model->find($uid);
        //必传参数
        $only = ['username', 'nickname', 'description', 'sex', 'qq', 'avatar_base64'];

        $rule = [
            'username|用户名' => 'length:4,16',
            'nickname|昵称' => 'length:2,10',
            'sex|性别' => 'between:0,2'
        ];
        $data = validate_ext($only, $rule);
        if (isset($data['code']) && $data['code'] === 0) {
            return json($data);
        }
        $upd_data2 = $returnData = [];
        if (isset($data['avatar_base64'])) {
            $resl = UploadService::upBase64($data['avatar_base64']);

            if ($resl['code'] != 1) {
                return json(array('code' => 0, 'msg' => '头像上传失败' . $resl['msg'], 'data' => []));
            }
            unset($data['avatar_base64']);
            //
            if ($find->avatar && strpos($find->avatar, 'http') === false) {
                @unlink(ROOT_PATH . '/public' . $find->avatar);
            }
            $data['avatar'] = $returnData['src'] = $resl['data']['url'];
        }
        if (isset($data['username']) && $data['username'] != $find->username) {
            $username_change_days = sysconfig('user.username_change_days');
            if ($username_change_days) {
                $usernameLastChange = (new UserAttribute())->where('user_id', $uid)->value('username_last_change');
                if ($usernameLastChange && ($usernameLastChange + $username_change_days * 86400) > time()) {
                    return json(array('code' => 0, 'msg' => '每' . $username_change_days . '只能改一次用户名', 'data' => []));
                }
            }

            if ($this->model->where('username', $data['username'])->count()) {
                return json(array('code' => 0, 'msg' => '已经有人使用该用户名', 'data' => []));
            }
            $upd_data2['username_last_change'] = time();
        }
        $this->model->where('id', $uid)->save($data);
        if (count($upd_data2)) {
            $model = (new UserAttribute())->where('user_id', $uid)->find();
            $model->save($upd_data2);
        }
        return json(array('code' => 1, 'msg' => '修改成功', 'data' => $returnData));
    }

    public function comment_data()
    {
        $data = $this->params;
        $aid = $data['aid'];


        //查询
        $where['status'] = 1;

//        $where['pid'] = 0;

        $where['subject_id'] = $aid;
        $_comments = (new Comment())
            ->where($where)
//                ->order('reply_num', 'desc')
            ->order('id', 'desc')
            ->select()->toArray();
        $comments = $comments_hot = $comments_reply = $commentIds = [];
        $commentNum = $commentHotNum = $replyNum = 0;
        foreach ($_comments as $v) {
            $commentIds[] = $v['id'];
            if ($v['support_num'] >= 5) {
                $commentHotNum++;
                $comments_hot[] = $v;
            } else {
                $commentNum++;
                $comments[] = $v;
            }
        }

        if (count($commentIds)) {

            $where2['status'] = 1;

            $comments_reply = (new Comment())->alias('a')
                ->whereIn('root_id', $commentIds)
                ->where($where2)
                ->order('id', 'desc')
                ->select();
            $replyNum = count($comments_reply);
        }
        //allow评论
        $result['allow'] = (new ArticleAttribute())->where('article_id', $aid)->value('allow_comment');
        $result['pages'] = 1;
        $result['count'] = $commentNum + $commentHotNum + $replyNum;
        $result['pl'] = $commentNum + $commentHotNum;
        $result['hf'] = $replyNum;
        $result['list']['comments'] = $comments;
        $result['list']['comments_hot'] = $comments_hot;
        $result['list']['comments_reply'] = $comments_reply;
        return json(array(
            'code' => 1,
            'msg' => '评论获取成功',
            'data' => $result,
        ));

    }

    public function praise()
    {
        $data = $this->params;

        $objectId=$data['id'];
        $objectType=$data['subject'];
        $badGood='';
        if(isset($data['type'])){
            $badGood=$data['type'];
        }
        $code = 1;

        $userId  = '';
        if (cacheUserid()) {
            $userId = cacheUserid();
        }
            $ip = $this->request->ip();


        $find = UserPraise::checkIsPraised($objectType, $objectId, $userId, $ip);
        if ($find) {
            $code = 2;
            $msg = '已点过赞了';
        } else {
            UserPraise::setIncPraise($objectType, $objectId, $userId,$badGood);
            $msg = '点赞成功';
        }

        return json(array(
            'code' => $code,
            'msg' => $msg,
            'data' => [],
        ));
    }
    public function comment(){
        $userId = $this->uid;
        //
        $config = sysconfig('comment');
        if ($config['must_login'] && !$userId) {
            return json(array(
                'code' => 0,
                'msg' => '没有登录',
                'data' => [],
            ));
        }
        $data = $this->params;
        $objectId = $data['aid'];
        $pid = isset($data['pid'])?$data['pid']:0;
        $code = 1;
        //id是否存在允许评论
        $allowPling = (new ArticleAttribute())->where('article_id', $objectId)->value('allow_comment');

        if (!$allowPling) {

            return json(array(
                'code' => 0,
                'msg' => '不允许评论',
                'data' => [],
            ));
        }
        $oobj = '有人评论了你的文章';
        $type=1;
        $parentId = $commentId = 0;

        if (isset($data['pid'])) {
            $parentId = $data['pid'];
            //
            $puid=(new Comment())->where('id',$pid)->value('user_id');
            $oobj = '有人回复了你的评论';
            $type=2;
        }else{
            $puid=(new Article())->where('id',$objectId)->value('user_id');
        }
        $authCheck = Comment::checkAuth($userId);
        if ($authCheck !== true) {
            return json(array(
                'code' => 0,
                'msg' => $authCheck['msg'],
                'data' => [],
            ));
        }
        $status = $code = 1;
        $msg = '评论成功';
        if ($config['check'] == 1) {
            $code = 2;
            $status = 0;
            $msg .= '，需要管理员审核才能发布';
        } else if ($config['check'] == 2 && isset($config['check_keywords'])) {

            $keywords = array_filter(explode(',', $config['check_keywords']));
            if (count($keywords)) {
                foreach ($keywords as $v) {
                    if (strpos($data['content'], $v) !== false) {
                        $code = 2;
                        $status = 0;
                        $msg .= '，由于含有不允许发布的关键字，需要管理员审核才能发布';
                        break;
                    }
                }
            }
        }
        $content=remove_xss($data['content']);
        $res = Comment::insertOne($content, 'ARTICLE', $objectId, $commentId, $parentId, $status, $userId);
       if($puid&&$puid!=$userId) {
           Message::note($oobj, '<a target="_blank" href="/html/' . $objectId . '.html">' . $content . '</a>', 0, $puid,$type);
       }
       return json(array(
            'code' => $code,
            'msg' => $msg,
            'data' => $res,
        ));
    }
}